import WangEditor from '@/components/WangEditor/index';
import {
  creatAnnotation,
  destoryAnnotation,
  getThesisById,
  queryAnnotationlist,
  updateAnnotation,
  updateThesisStatus,
} from '@/services/ThesisManage/thesisReview/ThesisController';
import { getScrollTop, getSiderWidth } from '@/utils/index';
import { storage } from '@/utils/Storage';
import { FieldTimeOutlined } from '@ant-design/icons';
import { ProList } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, message, Modal, Pagination, Popconfirm, Row } from 'antd';
import { saveAs } from 'file-saver';
import { useEffect, useRef, useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import { useParams } from 'umi';
import AnnotationForm from './components/AnnotationForm';
import ToolBar from './components/ToolBar';
import { addDefaultMark } from './constants/constants';
import styles from './detail.less';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

const ThesisDetail = () => {
  // const { name } = useModel('global');
  const locationParams = useParams();
  // pdf相关
  const [numPages, setNumPages] = useState(1); // pdf总共页数
  const [pageNumber, setPageNumber] = useState(1); // pdf当前页数
  const [file, setFile] = useState('');

  // 论文
  const [thesisDetail, setThesisDetail] = useState({});
  const [dataSource, setDataSource] = useState([]);
  // 工具栏
  const [toolSelect, setToolSelect] = useState('Text');
  const [drawType, setDrawType] = useState('Text');
  const [annotationStyle, setAnnotationStyle] = useState({});
  const [editorStyle, setEditorStyle] = useState({}); // 编辑器样式
  const [editorShow, setEditorShow] = useState(false);
  const canvasRef = useRef(null);
  const isMouseDownRef = useRef(false);
  const mouseDownTimeRef = useRef(null);
  const lastX = useRef(0);
  const lastY = useRef(0);

  const modalFormRef = useRef(null);
  const [permission, setPermission] = useState({ edit: false, view: false }); // 查看和编辑的权限

  const init = () => {
    getAnnotationlist().then((res) => {
      setDataSource(res.data);
    });
    getThesisDetail().then((res) => {
      const detail = res.data;
      let newPermission = null;
      const userInfo = storage.get('userInfo');
      newPermission = {
        edit: userInfo.id === detail.teacher_id,
        view:
          userInfo.id === detail.student_id ||
          userInfo.id === detail.teacher_id,
      };
      setThesisDetail(detail);
      setPermission(newPermission);
    });
  };

  const handleMouseDown = (event) => {
    const siderWidth = getSiderWidth();
    const scrollTop = getScrollTop();
    console.log(event, 'Down');
    isMouseDownRef.current = true;
    mouseDownTimeRef.current = Date.now();
    lastX.current = event.clientX - siderWidth - 24;
    lastY.current = event.clientY + scrollTop - 212;
  };

  const handleMouseMove = (event) => {
    if (isMouseDownRef.current) {
      const siderWidth = getSiderWidth();
      const scrollTop = getScrollTop();
      const currentX = event.clientX - siderWidth - 24;
      const currentY = event.clientY + scrollTop - 212;
      switch (drawType) {
        case 'Line':
          drawLine(lastX.current, lastY.current, currentX, currentY);
          break;
        case 'Rectangle':
          drawRectangle(lastX.current, lastY.current, currentX, currentY);
          break;
        default:
          break;
      }
      // lastX.current = currentX;
      // lastY.current = currentY;
    }
  };

  const handleMouseUp = (event) => {
    isMouseDownRef.current = false;
    if (Date.now() - mouseDownTimeRef.current > 200) {
      const siderWidth = getSiderWidth();
      const scrollTop = getScrollTop();
      const currentX = event.clientX - siderWidth - 24;
      const currentY = 841 - (event.clientY + scrollTop - 212);
      isMouseDownRef.current = false;
      Modal.confirm({
        title: '是否保存？',
        icon: false,
        onOk: async () => {
          const newDataSource = [...dataSource];
          let newSource = {};
          switch (drawType) {
            case 'Line':
              newSource = {
                thesis_id: thesisDetail.thesis_id,
                thesis_page_number: pageNumber,
                description: '直线',
                draw_type: 'Line',
                draw_content: JSON.stringify({
                  start: { x: lastX.current, y: 841 - lastY.current },
                  end: { x: currentX, y: currentY },
                  lineWidth: 3,
                }),
              };
              break;
            case 'Rectangle':
              newSource = {
                thesis_id: thesisDetail.thesis_id,
                thesis_page_number: pageNumber,
                description: '矩形',
                draw_type: 'Rectangle',
                draw_content: JSON.stringify({
                  x: lastX.current,
                  y: 841 - lastY.current,
                  width: currentX - lastX.current,
                  height: currentY + lastY.current - 841,
                  borderWidth: 2,
                }),
              };
              break;
            default:
              break;
          }
          clearCanvas();
          const res = await creatAnnotation(newSource);
          if (res.code === 200) {
            getAnnotationlist().then((res) => {
              setDataSource(res.data);
              setEditorShow(false);
            });
          }
        },
        onCancel: () => {
          clearCanvas();
        },
      });
    }
  };

  const clearCanvas = () => {
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
  };

  const drawLine = (startX, startY, endX, endY) => {
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.moveTo(startX, startY);
    context.lineTo(endX, endY);
    context.strokeStyle = '#F21919';
    context.stroke();
    context.closePath();
  };

  const drawRectangle = (startX, startY, endX, endY) => {
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.lineWidth = 1;
    context.strokeStyle = '#F21919';
    context.strokeRect(startX, startY, endX - startX, endY - startY);
  };

  const getThesisDetail = async () => {
    const thesis = await getThesisById(locationParams.id);
    return thesis;
  };

  const getAnnotationlist = async () => {
    const thesisList = await queryAnnotationlist({
      thesis_id: locationParams.id,
    });
    return thesisList;
  };

  const onDocumentLoadSuccess = ({ numPages }) => {
    setNumPages(numPages);
  };

  const onChange = (page) => {
    setPageNumber(page);
  };

  const handleUpdate = (row) => {
    Modal.confirm({
      title: '请输入修改内容',
      icon: false,
      content: (
        <AnnotationForm
          modalFormRef={modalFormRef}
          cItem={row}
        ></AnnotationForm>
      ),
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await modalFormRef?.current?.validateFields();
        const values = await modalFormRef?.current?.getFieldsValue();
        await updateAnnotation({
          annotation_id: row.annotation_id,
          description: values.description,
        });
        getAnnotationlist().then((res) => {
          setDataSource(res.data);
        });
        Modal.destroyAll();
      },
    });
  };

  const handleDoubleClick = (e) => {
    switch (drawType) {
      case 'Text':
        handleDrawText(e);
        break;
      default:
        break;
    }
  };

  const handleOneClick = (e) => {
    setEditorShow(false);
  };

  const handleOnMouseDown = (e) => {
    console.log(e);
  };

  const handleEditorSubmit = async (value) => {
    const newSource = {
      thesis_id: thesisDetail.thesis_id,
      thesis_page_number: pageNumber,
      description: value.replace(/<[^>]+>/g, '') || '',
      draw_type: 'Text',
      draw_content: JSON.stringify({
        ...annotationStyle,
      }),
    };
    const res = await creatAnnotation(newSource);
    if (res.code === 200) {
      getAnnotationlist().then((res) => {
        setDataSource(res.data);
        setEditorShow(false);
      });
    }
  };

  const selectTool = (name) => {
    setDrawType(name);
  };

  const handleDrawText = (e) => {
    const siderWidth = getSiderWidth();
    const scrollTop = getScrollTop();
    const { clientX, clientY } = e;
    const newEditorStyle = {
      top: `${clientY + scrollTop - 170}px`,
      left: `${clientX - siderWidth - 24}px`,
    };
    setEditorShow(true);
    setEditorStyle(newEditorStyle);
    setAnnotationStyle({
      x: clientX - siderWidth - 24,
      y: 841 - (clientY + scrollTop - 212),
    });
  };

  const handleDownload = (type) => {
    const token = storage.get('token');
    const fileUrl =
      type === 'origin'
        ? `/api/getPdf/${thesisDetail?.student_id}/${thesisDetail?.thesis_url}`
        : file;
    fetch(fileUrl, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
      .then((response) => response.blob())
      .then((blob) => {
        saveAs(blob, `${thesisDetail?.thesis_name}.pdf`);
      });
  };

  const handleCheckDone = async (type) => {
    const res = await updateThesisStatus({
      thesis_id: thesisDetail.thesis_id,
      thesis_status: '已完成',
    });
    if (res.code === 200) {
      message.success('操作成功！');
      init();
    }
  };

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    if (thesisDetail?.thesis_url) {
      const newFile = addDefaultMark(
        `${thesisDetail?.student_id}/${thesisDetail?.thesis_url}`,
        dataSource,
      );
      newFile.then((res) => {
        setFile(res);
      });
    }
  }, [JSON.stringify(dataSource), thesisDetail?.thesis_url]);

  useEffect(() => {
    if (drawType !== 'Text') {
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');

      // 设置Canvas元素背景为透明
      canvas.style.backgroundColor = 'transparent';

      canvas.addEventListener('mousedown', handleMouseDown);
      canvas.addEventListener('mousemove', handleMouseMove);
      canvas.addEventListener('mouseup', handleMouseUp);
      return () => {
        canvas.removeEventListener('mousedown', handleMouseDown);
        canvas.removeEventListener('mousemove', handleMouseMove);
        canvas.removeEventListener('mouseup', handleMouseUp);
      };
    } else {
      canvasRef.current = null;
    }
  }, [drawType, pageNumber]);

  return (
    <PageContainer>
      <Row className={styles.pageContent}>
        <Col
          xs={24}
          sm={24}
          md={13}
          lg={13}
          xl={13}
          className={styles.leftContent}
          style={{ width: '600px' }}
        >
          {permission.edit ? <ToolBar selectTool={selectTool}></ToolBar> : ''}
          {/* 文字输入框 */}
          {editorShow ? (
            <WangEditor
              editorStyle={editorStyle}
              closeEditor={handleOneClick}
              editorSubmit={handleEditorSubmit}
            />
          ) : (
            ''
          )}
          {drawType !== 'Text' ? (
            <canvas
              className={styles.canvas}
              ref={canvasRef}
              width={595}
              height={841}
            />
          ) : (
            ''
          )}

          <Document
            file={file}
            onLoadSuccess={onDocumentLoadSuccess}
            options={{
              cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
              cMapPacked: true,
            }}
            onDoubleClick={permission.edit ? handleDoubleClick : null}
            onClick={permission.edit ? handleOneClick : null}
            // onMouseDown={permission.edit ? handleOnMouseDown : null}
          >
            <Page width={595} height={841} pageNumber={pageNumber} />
          </Document>
          <Pagination
            simple
            style={{
              marginTop: '20px',
              height: '32px',
              lineHeight: '32px',
              textAlign: 'center',
            }}
            total={numPages}
            pageSize={1}
            onChange={onChange}
          />
        </Col>
        <Col xs={24} sm={24} md={11} lg={11} xl={11}>
          <div className={styles.buttonList}>
            {permission.edit && thesisDetail.thesis_status === '审查中' ? (
              <Button onClick={handleCheckDone}>审查完成</Button>
            ) : (
              ''
            )}
            <Button onClick={handleDownload.bind(this, 'pdf')}>pdf下载</Button>
            <Button onClick={handleDownload.bind(this, 'origin')}>
              源文件下载
            </Button>
          </div>
          <ProList
            onRow={(record) => {
              return {
                // onMouseEnter: () => {
                //   console.log(record);
                // },
                // onClick: () => {
                //   console.log(record);
                // },
              };
            }}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: false,
            }}
            rowKey="name"
            dataSource={dataSource}
            metas={{
              title: {
                dataIndex: 'thesis_page_number',
                render: (text, record) => {
                  return (
                    <span
                      onClick={() => {
                        setPageNumber(text);
                      }}
                    >
                      {`第${text}页`}
                    </span>
                  );
                },
              },
              avatar: {
                dataIndex: ['thesis', 'teacher_thesis', 'avatar'],
              },
              description: {
                dataIndex: 'description',
              },
              subTitle: {
                render: (text, record) => {
                  return (
                    <span>
                      <FieldTimeOutlined />
                      {record.created_at || '-'}
                    </span>
                  );
                },
              },
              actions: {
                render: (text, row) =>
                  permission.edit
                    ? [
                        <a
                          rel="noopener noreferrer"
                          key="edit"
                          onClick={handleUpdate.bind(this, row)}
                        >
                          编辑
                        </a>,
                        <Popconfirm
                          title="是否删除该批注"
                          onConfirm={async () => {
                            const res = await destoryAnnotation({
                              annotation_id: row.annotation_id,
                            });
                            getAnnotationlist().then((res) => {
                              setDataSource(res.data);
                            });
                          }}
                          okText="是"
                          cancelText="否"
                          key="delete"
                        >
                          <a rel="noopener noreferrer">删除</a>
                        </Popconfirm>,
                      ]
                    : [],
              },
            }}
          />
        </Col>
      </Row>
    </PageContainer>
  );
};

export default ThesisDetail;
